package com.example.controller;

import com.example.common.Result;
import com.example.entity.Attachment;
import com.example.service.AttachmentService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/attachments")
public class AttachmentController {

    @Resource
    private AttachmentService attachmentService;

    /**
     * 新增附件
     */
    @PostMapping("/add")
    public Result add(@RequestBody Attachment attachment) {
        attachmentService.save(attachment);
        return Result.success("附件保存成功");
    }

    /**
     * 查询单条附件
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable Integer id) {
        Attachment doc = attachmentService.getWithOpinions(id);
        return Result.success(doc);
    }

    /**
     * 分页查询附件列表（使用实体类封装查询条件，风格与ClassController一致）
     */
    @GetMapping("/selectPage")
    public Result selectPage(Attachment attachment,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Attachment> page = attachmentService.selectPage(attachment, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 删除单条附件
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        attachmentService.deleteById(id);
        return Result.success("收文删除成功");
    }

    /**
     * 批量删除附件
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        attachmentService.deleteBatch(ids);
        return Result.success("批量删除成功");
    }

    /**
     * 更新附件信息
     */
    @PutMapping("/update")
    public Result update(@RequestBody Attachment attachment) {
        attachmentService.updateById(attachment);
        return Result.success("收文更新成功");
    }

    /**
     * 查询预览附件
     */
    @GetMapping("/preview")
    public Result preview(@RequestParam Integer docId, @RequestParam String fileType) {
        Attachment attachment = new Attachment();
        if (fileType.equals("in")) {
            attachment.setDocId(docId);
            attachment.setFileType("收文附件");
        } else if (fileType.equals("out")) {
            attachment.setDocId(docId);
            attachment.setFileType("发文附件");
        }
        List<Attachment> attachments = attachmentService.preview(attachment);
        return Result.success(attachments);
    }
}
